package com.helloworld.chat.websocket;

import com.google.gson.Gson;
import com.helloworld.chat.Model.MsgModel;
import com.helloworld.chat.cache.CacheManager;
import com.helloworld.chat.cache.UnReadMessageCache;
import com.helloworld.chat.cache.UserCache;
import org.apache.log4j.Logger;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by xdzy on 2017/7/2.
 */
@ServerEndpoint("/webChat/{uid}")
public class WebSocket {
    private static final Logger logger=Logger.getLogger(WebSocket.class);
    private Session session;
    private String uid;
    private static Map<String,WebSocket> map=new ConcurrentHashMap<>();


    @OnOpen
    public void onOpen(@PathParam("uid") String uid, Session session){
        this.session=session;
        this.uid=uid;
        map.put(uid,this);
        UserCache userCache= CacheManager.getUserCache();
        userCache.changeUserStatus(uid,"0");
        System.out.println(uid+"建立了链接");
    }

    @OnClose
    public void onClose(){
        map.remove(uid+"");
        UserCache userCache= CacheManager.getUserCache();
        userCache.changeUserStatus(uid+"","0");
        userCache.changeChating(uid,"");
        System.out.println(uid+""+"关闭了连接");
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自"+uid+""+"的消息:" + message);
        Gson gson=new Gson();
        MsgModel msgModel=gson.fromJson(message,MsgModel.class);
        String to=msgModel.getTo();
        UserCache userCache= CacheManager.getUserCache();
        UnReadMessageCache urmCache=CacheManager.getUnReadMessageCache();
        if(userCache.isConnection(msgModel.getFrom(),msgModel.getTo())){
            try {
                map.get(to).sendMessage(new Gson().toJson(msgModel));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            urmCache.addUnReadMessage(to,msgModel);
            MsgModel adivce=new MsgModel();
            adivce.setType("advice");
            adivce.setContent("unread");
            adivce.setFrom(msgModel.getFrom());
            try {
               if(map.containsKey(to)){
                   map.get(to).sendMessage(new Gson().toJson(adivce));
               }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        //error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }
}

